﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Twitter;
using System.ComponentModel.Design;
using FriendsNearby.Services;
using FriendsNearby.Services.Facebook;
using InSTEDD.Labs.Geo;

namespace FriendsNearbyBot
{
    internal class FriendsProcessor : IMessageProcessor
    {
        IServiceProvider services;
        IMessageBuilder messageBuilder;

        public FriendsProcessor()            
            : this(new FriendsNearbyFacade(), new PlainTextMessageBuilder())
		{
		}

        public FriendsProcessor(IServiceProvider services, IMessageBuilder messageBuilder)
        {
            this.services = services;
            this.messageBuilder = messageBuilder;
        }

        public bool CanProcess(Message message)
        {
            return (message.Text == "friend" || message.Text == "friends" || message.Text == "contact" || message.Text == "contacts");
        }

        public RunNextProcessor Process(IBotClient client, Message message)
        {
            if (CanProcess(message))
            {
                string facebookId = services.GetService<IUsersService>().GetFacebookUserIdFromTwitter(message.Sender.ScreenName);

                messageBuilder.Clear();
                if (facebookId == null)
                {
                    // Warn the user via SMS that the mapping has not been established.
                    messageBuilder.AppendFragment(String.Format(Properties.Resources.TwitterNotMapped, message.Sender.ScreenName));
                    client.SendMessages(message.Sender.ScreenName, messageBuilder.GetMessages(), message, this.GetType().Name);
                }
                else
                {
                    int countFriendsNearby;
                    double? nearestDistance;

                    services.GetService<IPeopleNearbyService>().GetPeopleNearbySummary(facebookId,
                        out countFriendsNearby,
                        out nearestDistance);

                    messageBuilder.AppendFragment(String.Format(Properties.Resources.FriendsResponse, countFriendsNearby,
                        DistanceHelper.GetDistanceString(nearestDistance)).Pluralize());
                    client.SendMessages(message.Sender.ScreenName, messageBuilder.GetMessages(), message, this.GetType().Name);
                }

                BotProcessor.MessageProcessed(client, message);

                return RunNextProcessor.No;
 
            }
            else
                return RunNextProcessor.Yes;
        }
    }
}
